<script setup lang="ts">
import type { ComponentExposed } from 'vue-component-type-helpers'
import RecalculationForm from './RecalculationForm.vue'
import type {
  CalculationIndicatorRecalculationBatchIndicatorRecalculationParams as A,
  CustomDialogInstance,
} from '@/types'
import { calculationIndicatorRecalculationApi } from '@/api'
// ------------------use------------------
// #region
const props = defineProps<{
  selectionList: any[]
  timeType: string
}>()
const emits = defineEmits<{
  success: []
}>()
const { $message } = useCurrentInstance()
// #endregion
// ------------------静态变量------------------
// #region

// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const dialogRef = ref<CustomDialogInstance | null>(null)
const formRef
  = ref<ComponentExposed<typeof RecalculationForm>>()
// #endregion
// ------------------reactive------
// #region
// #endregion
// ------------------computed------
// #region
// #endregion
// ------------------生命周期------------------
// #region

// #endregion
// ------------------内置方法---------------------
// #region
// #endregion
// ------------------方法---------------------
// #region
async function open() {
  dialogRef.value?.open?.()
  await nextTick()
  dialogRef.value?.setSaving?.(false)
  formRef.value?.test?.({ key: props.timeType })
}
async function close() {
  formRef.value?.reset?.()
  await nextTick()
  dialogRef.value?.close?.()
}
async function clickSave(done: () => void) {
  try {
    const isValid = await formRef.value?.validate()
    if (!isValid) {
      done()
      return
    }
    await addOrUpdateData()
    done()
    emits('success')
    close()
    $message.success('重新计算已发起！')
  }
  catch (error) {
    done()
  }
}
async function addOrUpdateData() {
  const formData = formRef.value?.getData?.()!
  const { endTime, startTime, key } = unref(formData)
  const arr: A[] = props.selectionList.map((item) => {
    const { indicatorName, indicatorNumber } = item
    return {
      endTime,
      indicatorName,
      indicatorNumber,
      key,
      startTime,
    }
  })
  removeUnnecessaryParams(arr)
  await calculationIndicatorRecalculationApi.batchIndicatorRecalculation(
    arr,
  )
}
// #endregion
defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="发起批量重算"
    need-saving
    width="600px"
    @confirm="clickSave"
  >
    <RecalculationForm ref="formRef" />
  </CustomDialog>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
